package com.alan.shiro.service;

import com.alan.shiro.bean.Permission;
import com.alan.shiro.bean.Role;
import com.alan.shiro.bean.User;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Auther: Alan liu
 * @Date: 2018/12/11 19:20
 * @Description: UserService
 */
@Service
public class UserService {

    private static List<User> userList = new ArrayList<>();

    static {
        //初始化数据
        List<Permission> permissionsAll = new ArrayList<>();
        permissionsAll.add(new Permission(1L,"create",null));
        permissionsAll.add(new Permission(1L,"update",null));
        permissionsAll.add(new Permission(1L,"select",null));
        permissionsAll.add(new Permission(1L,"delete",null));
        Role roleUserAll = new Role();
        roleUserAll.setId(1L);
        roleUserAll.setRoleName("user");
        roleUserAll.setPermissions(permissionsAll);

        Role roleUserView = new Role();
        roleUserView.setId(2L);
        roleUserView.setRoleName("user");
        roleUserView.setPermissions(Arrays.asList(new Permission(1L,"select",null)));

        User user = new User();
        user.setId(1L);
        user.setName("alan");
        user.setPassword("123456");
        user.setRoles(Arrays.asList(roleUserAll));
        User userMd5 = new User();
        userMd5.setId(3L);
        userMd5.setName("alanMd5");
        //该密码是加密过后了的
        userMd5.setPassword("0caf568dbf30f5c33a13c56b869259fc");
        userMd5.setRoles(Arrays.asList(roleUserAll));
        User userView = new User();
        userView.setId(2L);
        userView.setName("alanView");
        userView.setPassword("123456");
        userView.setRoles(Arrays.asList(roleUserView));

        User admin = new User();
        admin.setId(3L);
        admin.setName("admin");
        admin.setPassword("123456");
        admin.setRoles(Arrays.asList(roleUserAll));

        userList.add(user);
        userList.add(userMd5);
        userList.add(userView);
        userList.add(admin);

    }


    public User findByName(String name) {
        for (User user : userList){
            if(user.getName().equals(name)){
                return user;
            }
        }
        return null;
    }

    public String getPassword(String username) {
        User user = findByName(username);
        if(user != null){
            return user.getPassword();
        }
        return null;
    }

    /**
     * shiro的密码加密，
     */
    public void passwrodMd5() {
        String hashAlgorithmName = "MD5";//加密方式
        Object crdentials = "123456";//密码原值
        Object salt = "abcd";//盐值
        int hashIterations = 2;//加密2次
        String result = new SimpleHash(hashAlgorithmName,crdentials,salt,hashIterations).toString();
        System.out.println(result);
    }

}
